import {request} from "../../request/index.js";
import {
  getSetting,
  openSetting,
  chooseAddress,
  showModal,
  showToast,
  requestPayment
} from "../../utils/asyncWx.js"
/*1获取用户收货地址
 *   1.绑定点击事件
 *   2. 调用小程序的内置api  获取用户的收货地址 wx.chooseAddress
 * 2.获取用户对小程序授予的获取地址的权限状态 scope
 *   1,假设 用户点击获取收货地址的提示框 确定 scope =true
 *   
 */
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取缓存的收货地址
    let address = wx.getStorageSync('address')
    //获取缓存的购物车数据
    let cart = wx.getStorageSync('cart') || []
    //获取过滤后的数组
    cart = cart.filter(v => v.checked);
    //1总价格 总数量
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price;
      totalNum += v.num;
    })
    this.setData({
      address,
      cart,
      totalPrice,
      totalNum
    })
    wx.setStorageSync('cart', cart)
  },

  //点击支付
  async handleOrderPay() {
    try {
      //判断缓存中有没有token
      // console.log(this.data.address.all);
      const token = wx.getStorageSync('token')
      //判断
      if (!token) {wx.navigateTo({  url: '/pages/auth/auth',});
        return
      };
      // console.log('已经有token');
      //创建订单
      // 1 准备请求头参数
      // const header = { Authorization: token}
      //2  准备请求体参数
      //	订单总价格
      const order_price = this.data.totalPrice;
      //	收货地址
      const consignee_addr = this.data.address.all;
      // 3 获取订单数组
      const cart = this.data.cart;
      let goods = [];
      cart.forEach(v => goods.push({
        //goods_id 商品id
        goods_id: v.goods_id,
        //goods_number 商品id
        goods_number: v.num,
        //单价
        goods_price: v.goods_price
      }))
      const orderParams = { order_price, consignee_addr, goods}
      // 4  发送请求 创建订单 获取订单编号
      const res = await request({ url: "/my/orders/create", data: orderParams, method: 'POST'})
      // console.log(res.data.message.order_number);
      const {order_number} = res.data.message
      // 5 发起预支付接口
      const result = await request({ url: "/my/orders/req_unifiedorder", method: "POST", data: {order_number}});
      const {pay} = result.data.message
      console.log(pay);
      // // 6 //发起微信支付
      const req= await  requestPayment(pay)
      console.log(req);
      // 7  查询订单状态
      const rejava = await request({ url: "/my/orders/chkOrder", method: "POST",data: {order_number}});
      console.log(rejava);
      //手动删除缓存中 已经支付的商品
      //  9 支付成功跳转订单页
      let newCart =wx.getStorageSync("cart")
      //过滤已经选中的 保存没有选中的 ,把没有选中的保存在缓存中
      newCart=newCart.filter(v=>!v.checked)
      wx.setStorageSync('cart',newCart)
      await showToast({title:'支付成功'})
      wx.navigateTo({
        url:'/pages/order/order'
      })
    } catch (error) {
      await showToast({ title: '支付失败' })
    }
  },
})